import { Injectable } from '@angular/core';
import { RestService } from '@abp/ng.core';
import { CreateUpdateKehuDto, KehuDto } from './models';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class KehuService {
  apiName = 'Default';
  
  // 添加缓存字段
  private listCache: {[key: string]: any} = {};
  private cacheTTL = 5 * 60 * 1000; // 缓存生存时间，默认5分钟
  private cacheTimestamps: {[key: string]: number} = {};
  
  constructor(private restService: RestService) {}

  // 生成缓存键
  private generateCacheKey(params: any, endpoint: string = 'list'): string {
    // 将params对象转换为排序后的查询字符串格式
    const sortedParams = Object.keys(params).sort().map(key => {
      return `${key}=${params[key]}`;
    }).join('&');
    
    return `${endpoint}:${sortedParams}`;
  }
  
  // 检查缓存是否有效
  private isCacheValid(key: string): boolean {
    if (!this.listCache[key] || !this.cacheTimestamps[key]) {
      return false;
    }
    
    const now = Date.now();
    return (now - this.cacheTimestamps[key]) < this.cacheTTL;
  }

  // 添加强制刷新选项
  getList(params: any = {}, forceRefresh: boolean = false): Observable<any> {
    // 生成缓存键
    const cacheKey = this.generateCacheKey(params);
    
    // 如果缓存有效且不强制刷新，则返回缓存
    if (!forceRefresh && this.isCacheValid(cacheKey)) {
      console.log('使用缓存数据:', cacheKey);
      return of(this.listCache[cacheKey]);
    }
    
    console.log('从服务器获取数据:', cacheKey);
    
    return this.restService.request<any, any>({
      method: 'GET',
      url: '/api/app/kehu',
      params
    }).pipe(
      tap(response => {
        // 存储到缓存
        this.listCache[cacheKey] = response;
        this.cacheTimestamps[cacheKey] = Date.now();
        console.log('数据已缓存:', cacheKey);
      })
    );
  }

  // 为搜索添加缓存支持
  searchByName(nameKeyword: string, params: any = {}, forceRefresh: boolean = false): Observable<any> {
    const searchParams = {
      nameKeyword,
      skipCount: params['skipCount'] || 0,
      maxResultCount: params['maxResultCount'] || 10,
      sorting: params['sorting'] || ''
    };
    
    // 生成缓存键
    const cacheKey = this.generateCacheKey(searchParams, 'search');
    
    // 如果缓存有效且不强制刷新，则返回缓存
    if (!forceRefresh && this.isCacheValid(cacheKey)) {
      console.log('使用搜索缓存数据:', cacheKey);
      return of(this.listCache[cacheKey]);
    }
    
    console.log('从服务器获取搜索数据:', cacheKey);
    
    return this.restService.request<any, any>({
      method: 'GET',
      url: '/api/app/kehu/search-by-name',
      params: searchParams
    }).pipe(
      tap(response => {
        // 存储到缓存
        this.listCache[cacheKey] = response;
        this.cacheTimestamps[cacheKey] = Date.now();
        console.log('搜索数据已缓存:', cacheKey);
      })
    );
  }

  // 在创建、更新和删除操作后清除缓存
  clearCache(): void {
    console.log('清除客户数据缓存');
    this.listCache = {};
    this.cacheTimestamps = {};
  }

  getById(id: string): Observable<KehuDto> {
    // 获取单个客户信息的缓存键
    const cacheKey = `detail:${id}`;
    
    // 如果缓存有效，则返回缓存
    if (this.isCacheValid(cacheKey)) {
      console.log('使用缓存的客户详情:', cacheKey);
      return of(this.listCache[cacheKey]);
    }
    
    return this.restService.request<any, KehuDto>({
      method: 'GET',
      url: `/api/app/kehu/${id}`
    }).pipe(
      tap(response => {
        // 存储到缓存
        this.listCache[cacheKey] = response;
        this.cacheTimestamps[cacheKey] = Date.now();
      })
    );
  }

  create(input: CreateUpdateKehuDto): Observable<KehuDto> {
    return this.restService.request<any, KehuDto>({
      method: 'POST',
      url: '/api/app/kehu',
      body: input
    }).pipe(
      tap(_ => this.clearCache()) // 创建后清除缓存
    );
  }

  update(id: string, input: CreateUpdateKehuDto): Observable<KehuDto> {
    return this.restService.request<any, KehuDto>({
      method: 'PUT',
      url: `/api/app/kehu/${id}`,
      body: input
    }).pipe(
      tap(_ => this.clearCache()) // 更新后清除缓存
    );
  }

  delete(id: string): Observable<void> {
    return this.restService.request<any, void>({
      method: 'DELETE',
      url: `/api/app/kehu/${id}`
    }).pipe(
      tap(_ => this.clearCache()) // 删除后清除缓存
    );
  }
} 